let localStream;
let remoteStream;
let peerConnection;
let dataChannel = null;

const configuration = {
    iceServers: [
        { urls: 'stun:stun.l.google.com:19302' }
    ]
};

// 获取 DOM 元素
const localVideo = document.getElementById('localVideo');
const remoteVideo = document.getElementById('remoteVideo');
const startButton = document.getElementById('startButton');
const callButton = document.getElementById('callButton');
const hangupButton = document.getElementById('hangupButton');
const statusDiv = document.getElementById('status');

// 添加事件监听
startButton.addEventListener('click', startCall);
callButton.addEventListener('click', call);
hangupButton.addEventListener('click', hangup);

async function startCall() {
    try {
        // 显示模态框并等待用户选择
        const roleModal = document.getElementById('roleModal');
        roleModal.style.display = 'block';

        const userChoice = await new Promise((resolve) => {
            document.getElementById('initiatorBtn').onclick = () => {
                roleModal.style.display = 'none';
                resolve(true);
            };
            document.getElementById('receiverBtn').onclick = () => {
                roleModal.style.display = 'none';
                resolve(false);
            };
        });

        isInitiator = userChoice;
        
        if (isInitiator) {
            try {
                localStream = await navigator.mediaDevices.getUserMedia({
                    video: true,
                    audio: true
                });
            } catch (err) {
                console.error('视频设备访问失败，尝试仅使用音频:', err);
                localStream = await navigator.mediaDevices.getUserMedia({
                    video: false,
                    audio: true
                });
                updateStatus('无法访问摄像头，将仅使用音频通话');
            }
        } else {
            localStream = await navigator.mediaDevices.getUserMedia({
                video: false,
                audio: true
            });
        }
        
        localVideo.srcObject = localStream;
        await localVideo.play().catch(e => console.log('本地视频播放失败:', e));
        startButton.disabled = true;
        callButton.disabled = !isInitiator;
        
        updateStatus(isInitiator ? '您是通话发起方' : '您是通话接收方');
    } catch (err) {
        console.error('获取媒体设备失败:', err);
        updateStatus('媒体设备访问失败');
        alert('无法访问媒体设备，请确保：\n1. 摄像头未被其他程序占用\n2. 已授予浏览器访问权限\n3. 设备正常连接');
    }
}

async function call() {
    console.log('开始建立连接，isInitiator:', isInitiator);
    callButton.disabled = true;
    hangupButton.disabled = false;

    peerConnection = new RTCPeerConnection(configuration);
    
    // 添加本地流
    localStream.getTracks().forEach(track => {
        peerConnection.addTrack(track, localStream);
    });

    // 监听连接状态变化
    peerConnection.onconnectionstatechange = () => {
        console.log('连接状态变化:', peerConnection.connectionState);
        updateStatus('连接状态: ' + peerConnection.connectionState);
    };

    peerConnection.oniceconnectionstatechange = () => {
        console.log('ICE连接状态:', peerConnection.iceConnectionState);
    };

    // 添加数据通道相关代码
    if (isInitiator) {
        console.log('创建数据通道');
        dataChannel = peerConnection.createDataChannel('chat');
        setupDataChannel(dataChannel);
    } else {
        console.log('设置数据通道接收监听');
        peerConnection.ondatachannel = (event) => {
            console.log('接收到数据通道');
            dataChannel = event.channel;
            setupDataChannel(dataChannel);
        };
    }

    // 监听远程流
    peerConnection.ontrack = event => {
        console.log('收到远程流');
        remoteVideo.srcObject = event.streams[0];
        remoteVideo.play().catch(e => console.log('远程视频播放失败:', e));
    };

    // 监听ICE候选者
    peerConnection.onicecandidate = event => {
        if (event.candidate) {
            console.log('发送ICE候选者');
            sendToSignalingServer({
                type: 'candidate',
                candidate: event.candidate
            });
        }
    };

    // 创建并发送 offer
    try {
        const offer = await peerConnection.createOffer();
        await peerConnection.setLocalDescription(offer);
        
        console.log('发送offer');
        sendToSignalingServer({
            type: 'offer',
            offer: offer
        });
    } catch (err) {
        console.error('创建 offer 失败:', err);
    }
}

function hangup() {
    if (peerConnection) {
        peerConnection.close();
        peerConnection = null;
    }
    
    // 停止所有媒体轨道
    if (localStream) {
        localStream.getTracks().forEach(track => track.stop());
        localStream = null;
    }
    
    // 清理视频源
    if (localVideo.srcObject) {
        localVideo.srcObject = null;
    }
    if (remoteVideo.srcObject) {
        remoteVideo.srcObject = null;
    }
    
    // 重置按钮状态
    startButton.disabled = false;
    callButton.disabled = true;
    hangupButton.disabled = true;
    
    // 通知对方挂断
    sendToSignalingServer({
        type: 'hangup'
    });

    if (dataChannel) {
        dataChannel.close();
        dataChannel = null;
    }

    // 重置聊天界面
    const messageInput = document.getElementById('messageInput');
    const sendButton = document.getElementById('sendButton');
    if (messageInput && sendButton) {
        messageInput.disabled = true;
        sendButton.disabled = true;
        messageInput.placeholder = '等待连接建立...';
    }
}

// 信令服务器连接（示例使用 WebSocket）
const ws = new WebSocket(`wss://${window.location.host}`);

ws.onmessage = async function(event) {
    try {
        const message = JSON.parse(event.data);
        console.log('收到WebSocket消息类型:', message.type);
        
        if (!peerConnection) {
            console.log('创建新的 PeerConnection');
            peerConnection = new RTCPeerConnection(configuration);
            
            // 添加本地流
            localStream.getTracks().forEach(track => {
                peerConnection.addTrack(track, localStream);
            });

            // 监听远程流
            peerConnection.ontrack = event => {
                console.log('收到远程流');
                remoteVideo.srcObject = event.streams[0];
            };

            // 添加数据通道处理
            if (!isInitiator) {
                peerConnection.ondatachannel = (event) => {
                    console.log('接收方：接收到数据通道');
                    dataChannel = event.channel;
                    setupDataChannel(dataChannel);
                };
            }
        }
        
        if (message.type === 'offer') {
            console.log('处理offer');
            await peerConnection.setRemoteDescription(new RTCSessionDescription(message.offer));
            const answer = await peerConnection.createAnswer();
            await peerConnection.setLocalDescription(answer);
            
            sendToSignalingServer({
                type: 'answer',
                answer: answer
            });
        } else if (message.type === 'answer') {
            console.log('处理answer');
            await peerConnection.setRemoteDescription(new RTCSessionDescription(message.answer));
        } else if (message.type === 'candidate') {
            console.log('处理ICE候选者');
            await peerConnection.addIceCandidate(new RTCIceCandidate(message.candidate));
        } else if (message.type === 'hangup') {
            console.log('对方已挂断');
            hangup();  // 执行本地挂断操作
        }
    } catch (error) {
        console.error('处理WebSocket消息时出错:', error);
    }
};

function sendToSignalingServer(message) {
    ws.send(JSON.stringify(message));
}

function updateStatus(message) {
    statusDiv.textContent = message;
}

ws.onopen = () => updateStatus('已连接到信令服务器');
ws.onclose = () => updateStatus('与信令服务器断开连接');
ws.onerror = () => updateStatus('信令服务器连接错误');

// 设置数据通道的事件处理
function setupDataChannel(channel) {
    console.log('设置数据通道，当前状态:', channel.readyState);
    
    channel.onopen = () => {
        console.log('数据通道已打开，状态：', channel.readyState);
        const messageInput = document.getElementById('messageInput');
        const sendButton = document.getElementById('sendButton');
        if (messageInput && sendButton) {
            messageInput.disabled = false;
            sendButton.disabled = false;
            messageInput.placeholder = '请输入消息...';
            updateStatus('聊天通道已开启');
        } else {
            console.error('找不到消息输入元素');
        }
    };

    channel.onclose = () => {
        console.log('数据通道已关闭，状态：', channel.readyState);
        const messageInput = document.getElementById('messageInput');
        const sendButton = document.getElementById('sendButton');
        if (messageInput && sendButton) {
            messageInput.disabled = true;
            sendButton.disabled = true;
            messageInput.placeholder = '等待连接建立...';
            updateStatus('聊天通道已关闭');
        }
    };

    channel.onerror = (error) => {
        console.error('数据通道错误：', error);
        updateStatus('聊天通道发生错误');
    };

    channel.onmessage = (event) => {
        console.log('收到消息：', event.data);
        displayMessage(event.data, false);
    };
}

// 发送消息
function sendMessage() {
    const input = document.getElementById('messageInput');
    const message = input.value.trim();
    
    if (message && dataChannel) {
        console.log('尝试发送消息，通道状态：', dataChannel.readyState);
        if (dataChannel.readyState === 'open') {
            try {
                dataChannel.send(message);
                displayMessage(message, true);
                input.value = '';
            } catch (error) {
                console.error('发送消息失败：', error);
                alert('发送消息失败，请重试');
            }
        } else {
            console.warn('数据通道未打开，状态：', dataChannel.readyState);
            alert('通信通道未准备好，请等待连接建立');
        }
    }
}

// 显示消息
function displayMessage(message, isSent) {
    const chatMessages = document.getElementById('chatMessages');
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${isSent ? 'sent' : 'received'}`;
    
    // 添加头像（仅接收方显示）
    if (!isSent) {
        const avatar = document.createElement('div');
        avatar.className = 'avatar';
        avatar.textContent = 'R'; // 可以替换为接收方名称首字母
        messageDiv.appendChild(avatar);
    }
    
    // 消息内容容器
    const contentContainer = document.createElement('div');
    contentContainer.className = 'content';
    contentContainer.textContent = message;
    messageDiv.appendChild(contentContainer);
    
    // 添加展开按钮（如果内容超过最大高度）
    if (contentContainer.scrollHeight > 200) {
        const expandButton = document.createElement('button');
        expandButton.className = 'expand-button';
        expandButton.textContent = '展开全文';
        expandButton.onclick = () => {
            messageDiv.classList.toggle('expanded');
            expandButton.textContent = messageDiv.classList.contains('expanded') ? '收起' : '展开全文';
        };
        messageDiv.appendChild(expandButton);
    }
    
    // 添加时间戳
    const timestamp = document.createElement('div');
    timestamp.className = 'timestamp';
    timestamp.textContent = new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
    messageDiv.appendChild(timestamp);
    
    chatMessages.appendChild(messageDiv);
    chatMessages.scrollTop = chatMessages.scrollHeight;
}

// 添加事件监听器
document.addEventListener('DOMContentLoaded', () => {
    const sendButton = document.getElementById('sendButton');
    const messageInput = document.getElementById('messageInput');

    // 确保元素存在
    if (!sendButton || !messageInput) {
        console.error('找不到聊天相关的DOM元素');
        return;
    }

    sendButton.addEventListener('click', sendMessage);
    messageInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });

    // 初始时禁用输入和发送
    messageInput.disabled = true;
    sendButton.disabled = true;
    
    // 添加占位符文本
    messageInput.placeholder = '等待连接建立...';
});